<script setup lang="ts">
import { ref,onMounted,onUpdated } from 'vue'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'

let isShow = ref(false);

let isInit=false;

let showView=()=>{
    if(isInit){
        return;
    }
    isInit=true;

    // A Yjs document holds the shared data
    const ydoc = new Y.Doc()

    // connect to the public demo server (not in production!)
    const provider = new WebsocketProvider(
        'ws://localhost:1234', 'quill-editor-room-1', ydoc
    )

    provider.on('status', event => {
        console.log(`ws status:${event.status}`) // logs "connected" or "disconnected"
    })

    const doc1 = new Y.Doc()
    const doc2 = new Y.Doc()

    doc1.on('update', update => {
        Y.applyUpdate(doc2, update)
    })

    doc2.on('update', update => {
        Y.applyUpdate(doc1, update)
    })

    console.log(doc1.getArray('myarray').toJSON());
    console.log(doc2.getArray('myarray').toJSON());
    // All changes are also applied to the other document
    doc1.getArray('myarray').insert(0, ['Hello doc2, you got this?'])
    doc2.getArray('myarray').insert(0, ['Hello doc1, you got this?'])
    console.log(doc1.getArray('myarray').toJSON());
    console.log(doc2.getArray('myarray').toJSON());
    doc2.getArray('myarray').get(0) // => 'Hello doc2, you got this?'
    console.log(doc1.getArray('myarray').toArray());
    console.log(doc2.getArray('myarray').toArray());
}

onMounted(()=>{
    
})

onUpdated(()=>{
    if(isShow.value==true){
        showView();
    }
})

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 7`" @click="isShow = !isShow"></div>
    <div v-show ="isShow">
        <div class="desc">Y JS 示例 ：Example: Listen to update events and apply them on remote client 示例：侦听更新事件并将其应用于远程客户端,需要执行 yarn run websocket</div>
    </div>
</template>

<style scoped>
/* @import './styles/katex.min.css'; */
/* @import './styles/monokai-sublime.min.css'; */
.users {
    font-weight: bold;
    margin: 1em 1em;
}
  
.editor{
    width:600px;
    height:400px;
}
</style>